<template>
  <div id="SelectDataList">
    <el-popover :title="props.title" v-model:visible="visibleOutReporter" :width="400" trigger="click" placement="right">
      <template #reference>
        <el-input class="findDataListInput" ref="inputEmployeeRef" slot="reference" v-model="inputValue" :placeholder="props.placeholder" @keyup="keyupHandler" type="text" @input="inputHandler" @focus="focusHandler" clearable @clear="clearHandler" :style="{ width: props.inputWidth }"></el-input>
      </template>
      <vxe-table class="mytable-scrollbar" ref="ListTable" border v-loading="sLoading" show-header-overflow show-overflow max-height="400px" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{ isArrow: true }" @current-change="handleClickRow" :data="dataList">
        <vxe-column v-for="(item, index) in props.displayField" :key="index" :field="item.props" :title="item.title" align="center" :width="item.width"></vxe-column>
      </vxe-table>

      <vxe-pager v-if="props.isPage" min-height="32px" style="margin-top: 10px" v-model:current-page.sync="pageIndex" :total="totalCount" :page-sizes="pageSizeList" v-model:page-size.sync="pageSizeCur" :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']" @page-change="handleSizeChange"></vxe-pager>
    </el-popover>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, getCurrentInstance, onMounted, watch } from 'vue';
import { pageSizes, IsEmpty } from '../utils/common';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';

// defineExpose(() => {});

let inputValue = ref('');
let props = defineProps({
  url: String, //请求地址
  displayField: Array as () => String[], //动态列和字段名1
  searchParam: {}, //接口参数{key1:value1,key2:value2...}
  isPage: { type: Boolean, default: false }, //是否需要分页
  modelValue: { type: String, default: '' }, //输入框绑定参数
  inputKeyName: String, //查询入参名称
  title: { type: String, default: '点击选择' }, //弹框标题
  inputWidth: { type: String, default: '200px' }, //输入框长度
  placeholder: { type: String, default: '' } //输入框默认文字
}) as any;
watch(
  () => props.modelValue,
  (newval, oldvbal) => {
    inputValue.value = newval;
  },
  {
    deep: true,
    immediate: true
  }
);

let pageSizeList = ref(pageSizes);
let pageSizeCur = ref(pageSizes[0]);
let pageIndex = ref(1);
let totalCount = ref(0);
let sLoading = ref(false);
let { proxy }: any = getCurrentInstance();
let dataList = reactive([]);
let visibleOutReporter = ref(false);
let url = props.url; // url地址

function findDataList() {
  dataList.length = 0;
  sLoading.value = true;
  // 请求参数
  let params: any = {
    pageSize: pageSizeCur.value,
    pageIndex: pageIndex.value,
    seachValue: inputValue.value
  };
  // inputValue.value = props.modelValue;
  // 循环父组件传来的参数，添加到参数对象中(data，params)
  if (!IsEmpty(props.searchParam)) {
    for (const key in props.searchParam) {
      if (props.searchParam[key]) {
        params[key] = props.searchParam[key];
      }
    }
  }
  if (!IsEmpty(props.inputKeyName)) {
    params[props.inputKeyName] = inputValue.value;
  }

  proxy.$http
    .get(url, { params })
    .then((res: any) => {
      sLoading.value = false;
      if (res.status.code !== 1 && res.status.code !== 200) {
        VxeMessage('获取列表失败', VxeNotifyType.error);
      } else {
        dataList.length = 0;
        if (props.isPage) {
          dataList.push(...res.data.records);
          totalCount.value = res.data.total;
        } else {
          dataList.push(...res.data);
        }
      }
      let $Xtable = proxy.$refs.ListTable;
      // $Xtable.setCurrentRow(dataList[0]);
      $Xtable.focus();
    })
    .catch((err) => {
      sLoading.value = false;
      VxeMessage('获取列表失败', VxeNotifyType.error);
    });
}

// 输入框获取焦点事件
function focusHandler() {
  findDataList();
}

//点击表格当前行，传递选中行给父组件
function handleClickRow({ row, rowIndex }) {
  proxy.$emit('selectDataRow', row);
  // inputValue.value = row.code;
  visibleOutReporter.value = false;
}

// 输入框值发生改变事件
function inputHandler() {
  findDataList();
}
// 输入框keyup事件
function keyupHandler($event) {
  // if ($event.code === 'Backspace') {
  //   proxy.$nextTick(() => {
  //     if (inputValue.value.length > 0) {
  //       let newStr = inputValue.value.slice(0, -1);
  //       inputValue.value = newStr;
  //     }
  //     proxy.$emit('sliceValue');
  //     findDataList();
  //   });
  // }
  if ($event.code === 'Backspace') {
    proxy.$emit('sliceValue'); // 仅通知父组件处理删除操作，不再直接调用findDataList
  }
}
//点击每页数量
function handleSizeChange({ type, currentPage, pageSize, $event }) {
  if (type === 'size') {
    pageIndex.value = 1;
  } else {
    pageIndex.value = currentPage;
  }
  pageSizeCur.value = pageSize;
  findDataList();
}

// 修改子组件的值并触发事件
function updateChildValue() {
  proxy.$emit('update:modelValue', inputValue.value);
}
// 点击输入框右侧按钮清空数据事件
function clearHandler() {
  inputValue.value = '';
  proxy.$emit('clearValue');
}
</script>
<style lang="scss" scoped>
#SelectDataList {
  height: 100%;
  width: 100%;
}
</style>
